<template>
    <div class="signUp">
        <b-modal class="b-modal" ref="b-modal-signUp" title="WeBlog注册">
            <div class="select"><button ref="phone" @click="changeWay('phone')">手机注册</button><button ref="email" @click="changeWay('email')">邮箱注册</button></div>
            <b-form>
                <b-form-group
                    :label="tips.wayName"
                    label-for="account"
                    :description="tips.accountDesc"
                >
                    <b-form-input 
                        id="account"
                        v-model="signUpForm.account"
                        :state="state_forAccount()"
                    >
                    </b-form-input>
                    <b-form-invalid-feedback :state="state_forAccount()">
                        请输入正确的账号格式
                    </b-form-invalid-feedback>
                </b-form-group>
                <b-form-group
                    label="密码："
                    label-for="password"
                    description="密码由字母、字符和下划线组成，必须包含数字和字母"
                >
                    <b-form-input 
                        id="password" 
                        type="password"
                        v-model="signUpForm.password"
                        :state="state_forpassword()"
                    >
                    </b-form-input>
                    <b-form-invalid-feedback :state="state_forpassword()">
                        密码由10-16位数和字母组成
                    </b-form-invalid-feedback>
                </b-form-group>
                <b-form-group
                    label="确认密码："
                    label-for="password"
                >
                    <b-form-input 
                        id="password" 
                        type="password"
                        v-model="signUpForm.repeatpassword"
                        :state="state_forRepeatpassword()"
                    >
                    </b-form-input>
                    <b-form-invalid-feedback :state="state_forRepeatpassword()">
                        密码不一致
                    </b-form-invalid-feedback>
                </b-form-group>
                <b-form-group
                    label="验证码："
                    label-for="testCode"
                >
                    <b-form-input
                        id="testCode" 
                        v-model="signUpForm.testCode"
                        :state="state_forcode()"
                    >
                    </b-form-input>
                    <b-form-invalid-feedback :state="state_forcode()">
                        验证码错误
                    </b-form-invalid-feedback><br>
                    <b-button @click="tips.testCodeCount < 60? null: test()" :variant="tips.tcb_variant">{{tips.testCodeName}}</b-button>
                </b-form-group>
            </b-form>
            <template v-slot:modal-footer>
                <b-button variant="info" @click="signUp">注册</b-button>
                <b-button @click="$emit('onChange', false)" variant="success">已有账号</b-button>
            </template>
        </b-modal>
    </div>
</template>

<script>

import Axios from 'axios';
import { signUp } from '@/../api/api.js'

export default {
    data() {
        return {
            code: null,
            status: {
                testCode:false,
                accountStatus:false,
                passwordStatus:false,
                repeatpasswordStatus:false,
            },
            signUpForm: {
                account: "",
                password: "",
                repeatpassword: "",
                testCode: ""
            },
            tips: {
                way: "phone",
                wayName: "手机号",
                accountDesc: "",
                testCodeName: "获取手机验证码",
                testCodeCount: 60,
                tcb_variant: "success"
            },
        }
    },
    methods: {
        changeSignUp(opt) {
            if(opt == "open") {
                this.$refs['b-modal-signUp'].show();
                this.tips['way'] = "phone",
                this.tips['wayName'] = "手机号";
                this.tips["accountDesc"] = "";
            }else if(opt == "close") {
                this.$refs['b-modal-signUp'].hide();
            }
        },
        // 注册方式（邮箱或手机号）
        changeWay(way) {
            if(way == "phone") {
                this.tips.wayName = "手机号";
                this.tips.testCodeName = "获取手机验证码"
                this.$refs['phone'].style.borderBottom= "1px solid #ccc";
                this.$refs['email'].style.borderBottom= "none";
                this.tips.accountDesc = "";
                this.tips.way = "phone";
            }else if(way == "email") {
                this.tips.wayName = "电子邮箱";
                this.tips.testCodeName = "获取邮箱验证码"
                this.$refs['phone'].style.borderBottom= "none";
                this.$refs['email'].style.borderBottom= "1px solid #ccc";
                this.tips.accountDesc = "目前仅支持qq、163邮箱注册";
                this.tips.way = "email";
            }
        },
        test() {
            if(this.status.accountStatus){
                Axios.post(signUp,{
                    'userAccount': this.signUpForm.account,
                    'userIdentityType': this.tips.way,
                    })
                .then(response => {
                    this.code = response.data.data.code;
                })
                .catch(() => {
                    window.alert('验证码获取失败，请稍后重试！');
                });
                let inter = setInterval(() => {
                    this.tips.testCodeName = "请等待：" + --this.tips.testCodeCount + "s";
                    this.tips.tcb_variant = "";
                    if(this.tips.testCodeCount == 0) {
                        this.tips.testCodeName = "重新获取验证码";
                        this.tips.testCodeCount = 60;
                        this.tips.tcb_variant = "success";
                        clearInterval(inter);
                    }
                }, 1000);
            }
        },
        // 注册弹窗的状态（用户名）
        state_forAccount() {
            if(this.signUpForm.account.length == 0) {
                return null;
            }
            if(this.tips.way == "phone") {
                if(/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/.test(this.signUpForm.account)) {
                    this.status.accountStatus = true;
                    return true;
                }
            }else if(this.tips.way == "email") {
                if(/^[1-9]{4,16}@qq.com/.test(this.signUpForm.account) || /^[0-9a-z]{0,255}@163.com/i.test(this.signUpForm.account)) {
                    this.status.accountStatus = true;
                    return true;
                }
            }
            return false;
        },
        // 注册弹窗的状态（密码）
        state_forpassword() {
            if(this.signUpForm.password.length == 0) {
                return null;
            }
            else if(/^[\w]{10,16}$/.test(this.signUpForm.password) && /[a-z]/.test(this.signUpForm.password) && /[0-9]/.test(this.signUpForm.password)) {
                this.status.passwordStatus = true;
                return true;
            }
            return false;
        },
        state_forRepeatpassword() {
            if(this.signUpForm.repeatpassword.length == 0) {
                return null;
            }
            else if(this.signUpForm.repeatpassword == this.signUpForm.password) {
                this.status.repeatpasswordStatus = true;
                return true;
            }
            return false;
        },
        // 注册验证码
        state_forcode() {
            if(this.signUpForm.testCode.length == 0) {
                return null;
            }
            else if(this.signUpForm.testCode == this.code && this.signUpForm.testCode != null) {
                this.status.testCode = true;
                return true;
            }
            return false;
        },
        //注册操作
        signUp() {
            if(this.status.accountStatus && this.status.passwordStatus && this.status.repeatpasswordStatus && this.status.testCode){
                Axios.post(signUp,{
                    'userAccount': this.signUpForm.account,
                    'userPassword': this.signUpForm.password,
                    'userIdentityType': this.tips.way,
                    })
                .then(Response => {
                    if (Response.data.message == 'success') {
                        window.alert('注册成功！'); 
                        this.$refs['b-modal-signUp'].hide();   
                    }
                    else if(Response.data.message == 'accountFailed'){
                        window.alert('账号已存在！');
                    }
                    else {
                        window.alert('注册失败，请检查相关信息或稍后重试！');
                    }
                })
                //错误提示
                .catch(err => {
                    window.alert('注册失败，请检查相关信息或稍后重试！');
                });
            }
        }
    }
}
</script>

<style lang="stylus" scoped>
.testCode-image
    max-width 320px

.select
    text-align center
    padding-bottom 18px
    >button
        height 32px
        background-color #fff
        outline none
        position relative
        font-size 17px
        color #757575
        box-sizing border-box
        &:nth-child(1)
            border-bottom 1px solid #ccc

</style>